package cn.showplus.controller;

import com.alibaba.fastjson.JSONObject;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Calendar;
import java.util.Map;
import java.util.UUID;

/**
 * Created by sunfeihu on 2017/5/5.
 */
@RestController
public class HomeController {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    public String jm() {
        String appId = "";
        String sessionKey = "";
        String encryptedData = "A4my9s9gOIpp1SI/4303WwhLvsXh0Skggq82/47hBbATs/AO45nCthD0CutLlrUz8GUZGmdHFLCoym1oktl2Nb3zMwwEhvGipPzAzsK0fZxiCUtndiCb2MH71JEpgGO0vlAvwQGMkY5yzleYbuA8KZ4kxz/VaoPjnUtNKnOeWeW9WsN7IzqR5dyCIzZLn3CcZW3SyfbSfuruqNXsZYmM6xk5SBWEg4XpOTaNRfmbxgAzYpPjvd80+LaQofVR+FOXgbXZVS9SWP3SR/SZKG//f+X4TWlt5lhrPEIT9xbVEaj1DCQhjVuuccLh1j3G8UO5XKkp7bemOWDOhgW12qvGZRBjEcGhXPrwQ7i5norsPS0c0apuCYR96oDzusBVIrp1zfr/aJO+2XOZeeqpx1jEnjh4H6BlpPygJHbdI07aybXYogcTUnWfDs4JTvc8FOZ80TITPI2zJ7j3zL0fGIjzERy8/rZrOZLcDEC82VwwqRo=";
        return null;
    }

    @GetMapping(value = "/data/{id}")
    public String data(@PathVariable Long id) {
        Map<String, Object> map = null;
        try {
            map = jdbcTemplate.queryForMap("select * from datas where id = ? ", new Object[]{id});
        } catch (Exception e) {
            e.printStackTrace();
        }
        JSONObject obj = new JSONObject();
        if (null != map) {
            obj = (JSONObject) JSONObject.toJSON(map);
        }
        return obj.toJSONString();
    }

    @PostMapping(value = "/add", produces = "application/json")
    public String savetxt(HttpServletRequest request) {
        KeyHolder keyHolder = new GeneratedKeyHolder();
        final String sql = " insert into datas(name,content,template_id,video_url,type,add_date) values(?,?,?,?,?,?)";
        final String fname = request.getParameter("name");
        final String fcontent = request.getParameter("content");
        final String ftemplateId = request.getParameter("templateId");
        final String fvideoUrl = request.getParameter("videoUrl");
        jdbcTemplate.update(new PreparedStatementCreator() {
            @Override
            public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
                PreparedStatement ps = connection.prepareStatement(sql, PreparedStatement.RETURN_GENERATED_KEYS);
                ps.setObject(1, fname);
                ps.setObject(2, fcontent);
                ps.setObject(3, ftemplateId);
                ps.setObject(4, fvideoUrl);
                ps.setObject(5, "txt");
                ps.setObject(6, Calendar.getInstance().getTime());
                return ps;
            }
        }, keyHolder);
        Long id = keyHolder.getKey().longValue();
        JSONObject obj = new JSONObject();
        obj.put("id", id);
        return obj.toJSONString();
    }

    @PostMapping(value = "/upload")
    public String upload(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        String realPath = ClassUtils.getDefaultClassLoader().getResource("").getPath();
        realPath = realPath + File.separator + "upload";
        File folder = new File(realPath);
        if (!folder.exists()) {
            folder.mkdirs();
        }
        String ext = file.getOriginalFilename();
        ext = ext.substring(ext.lastIndexOf("."));
        String name = folder.getAbsolutePath() + File.separator + UUID.randomUUID().toString().replaceAll("-", "") + ext;
        if (!file.isEmpty()) {
            try {
                byte[] bytes = file.getBytes();
                File f = new File(name);
                BufferedOutputStream stream =
                        new BufferedOutputStream(new FileOutputStream(f));
                stream.write(bytes);
                stream.close();
                String str = this.to7niu(f);
                if (str.startsWith("https://")) {
                    FileUtils.deleteQuietly(f);
                }
                if (str.startsWith("https://")) {
                    final String fUrl = str;
                    final String desc = request.getParameter("desc");
                    final String ftemplateId = request.getParameter("template_id");
                    final String ftype = request.getParameter("t");
                    final String fname = request.getParameter("name");
                    final String sql = " insert into datas (`video_url`,`content`,`template_id`,`type`,`name`,`add_date`) values(?,?,?,?,?,?)";
                    KeyHolder keyHolder = new GeneratedKeyHolder();
                    jdbcTemplate.update(new PreparedStatementCreator() {
                        @Override
                        public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
                            PreparedStatement ps = connection.prepareStatement(sql, PreparedStatement.RETURN_GENERATED_KEYS);
                            ps.setObject(1, fUrl);
                            ps.setObject(2, desc);
                            ps.setObject(3, ftemplateId);
                            ps.setObject(4, ftype);
                            ps.setObject(5, fname);
                            ps.setObject(6,Calendar.getInstance().getTime());
                            return ps;
                        }
                    }, keyHolder);
                    Long id = keyHolder.getKey().longValue();
                    return id + "";
                }
                return "";
            } catch (Exception e) {
                e.printStackTrace();
                return "You failed to upload " + name + " => " + e.getMessage();
            }
        } else {
            return "You failed to upload " + name + " because the file was empty.";
        }
    }

    private String to7niu(File f) {
        Configuration cfg = new Configuration(Zone.zone0());
        UploadManager uploadManager = new UploadManager(cfg);
        String accessKey = "YypKleT7M9lTYTyWMwwytmM7x9Uit9rUMK3c54L9";
        String secretKey = "aeMk8Q-CyhUGdLdZdNbNqqNMRJNOdxz7raicBidJ";
        String bucket = "videos";
        String localFilePath = f.getAbsolutePath();
        String key = null;
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);
        String str = "";
        try {
            Response response = uploadManager.put(localFilePath, key, upToken);
            JSONObject obj = JSONObject.parseObject(response.bodyString());
            str = "https://resource.lily0.com/" + obj.getString("hash");
        } catch (QiniuException ex) {
            str = ex.getMessage();
            ex.printStackTrace();
        }
        return str;
    }

}